package com.yanqu.service;

import com.yanqu.file.FileConfig;
import com.yanqu.file.LoggerConsumer;
import com.yanqu.file.RotateMode;
import com.yanqu.road.utils.ConfigHelper;

/**
 * 去掉线程池，让请求阻塞，避免oom，可以慢，不能挂
 */
public class DataFileWrite {

    LoggerConsumer loggerConsumer;

    public void add(StringBuffer stringBuffer){
        loggerConsumer.add(stringBuffer);
    }

    public void add(StringBuilder stringBuilder){
        loggerConsumer.add(stringBuilder);
    }

    public DataFileWrite() {
        init();
    }

    public void init(){

        //根目录不加serverId
        String logDirectory = ConfigHelper.getValue("logDirectory");
        //写文件锁
        String lockFileName = ConfigHelper.getValue("lockFileName");
        //及文件需加serverId
        String fileNamePrefix = ConfigHelper.getValue("fileNamePrefix");

        int fileSize = ConfigHelper.getInt("fileSize");

        FileConfig config = new FileConfig(logDirectory, fileSize);
        String rotateMode = ConfigHelper.getValue("rotateMode");
        config.setRotateMode("DAILY".equals(rotateMode)? RotateMode.DAILY : RotateMode.HOURLY);
        config.setAutoFlush("true".equals(ConfigHelper.getValue("autoFlush")));
        config.setInterval(ConfigHelper.getInt("interval"));
        config.setFilenamePrefix(fileNamePrefix);
        config.setFileSize(ConfigHelper.getInt("fileSize"));
        config.setBufferSize(ConfigHelper.getInt("bufferSize"));
        config.setLockFile(lockFileName);

        loggerConsumer = new LoggerConsumer(config);
    }

    public void close(){
        if(loggerConsumer != null){
            loggerConsumer.close();
        }
    }

}
